package com.tanhua.dubbo.api.Impl;

import com.itheima.dubbo.api.VisitorsApi;
import com.tanhua.model.mongoDb.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Author Pan Rundong
 * @Date 2023-03-06 21:37
 * @Desc 访客Api实现类
 */
@DubboService
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存访客信息，一天只能存一次
     *
     * @param visitors
     * @return void
     * @Author Pan Rundong
     */
    @Override
    public void save(Visitors visitors) {
        //1.判断当天是否已经储存
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        if (mongoTemplate.exists(query, Visitors.class)) {
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 最近访客
     *
     * @param date
     * @param userId
     * @return java.util.List<com.tanhua.model.mongoDb.Visitors>
     * @Author Pan Rundong
     */
    @Override
    public List<Visitors> visitors(Long date, Long userId) {
        //1.根据用户Id查询访客信息
        Criteria criteria = Criteria.where("userId").is(userId);

        //2.如果date不为null，则查询大于这个时间的值
        if (date != null) {
            criteria.and("date").is(date);
        }

        //3.查询
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("date"))).limit(5);
        return mongoTemplate.find(query, Visitors.class);
    }
}
